﻿using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Random = UnityEngine.Random;

class MainPlayerControl : SceneFightObject
{
    private Camera mainCamera;

    [SerializeField]
    private int speed = 5;

    private Rigidbody Myrigidbody;

    private float cameraRotete;

    private Animator animator;
    private AnimatorStateInfo animatorState;
    
    public bool isRun;
    public bool isAttack;
    public bool isDead;
    public bool isStand
    {
        get
        {
            return !isRun && !isAttack && !isDead;
        }
    }

    private string[] attackName = {"Attack", "Attack2" };

    private void Start()
    {
        Myrigidbody = GetComponent<Rigidbody>();
        animator = GetComponent<Animator>();
        mainCamera = Camera.main;
        Mgr.fightMgr.fightEvent.AddListener(FightEvent.RESPLAYERFIGHTRESULT, ResFightResult);
    }


    private void FixedUpdate()
    {
        //人物移动
        Vector3 vel = Myrigidbody.velocity;
        float v = Input.GetAxis("Vertical");
        float h = Input.GetAxis("Horizontal");

        if (v != 0 || h != 0)
        {
            float sr = Mathf.Sin(cameraRotete);
            float cr = Mathf.Cos(cameraRotete);
            Myrigidbody.velocity = new Vector3((v * sr + h * cr) * speed, vel.y, (v * cr - h * sr) * speed);
            transform.rotation = Quaternion.LookRotation(new Vector3((v * sr + h * cr), 0, (v * cr - h * sr)));
            isRun = true;
        }
        else
        {
            isRun = false;
        }
    }

    private void Update()
    {
        animatorState = animator.GetCurrentAnimatorStateInfo(0);

        if (Input.GetKeyDown(KeyCode.Mouse0))
        {
            Mgr.fightMgr.UseSkill(EnumSkillId.normol);
        }else if(Input.GetKeyDown(KeyCode.Alpha1))
        {
            Mgr.fightMgr.UseSkill(EnumSkillId.skill1);
        }
        else if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            Mgr.fightMgr.UseSkill(EnumSkillId.skill2);
        }

        if (isRun)
        {
            if (!animatorState.IsName("Run"))
            {
                animator.SetBool("Run", true);
            }
        }
        else
        {
            animator.SetBool("Run", false);
        }
        GameObject monster = GameObject.FindGameObjectWithTag("Monster");
        if(monster != null)
        {
            MonsterDis = Vector3.Distance(transform.position, monster.transform.position);
        }
    }

    public float MonsterDis;

    private void LateUpdate()
    {
        cameraRotete = mainCamera.transform.eulerAngles.y / 180 * Mathf.PI;
    }

    //接收到战斗结果
    private void ResFightResult(object data)
    {
        if(data != null)
        {
            AttackInfo info = data as AttackInfo;

        }
        animator.SetTrigger(attackName[Random.Range(0, attackName.Length)]);
    }

    public override void Recycle()
    {

    }
}
